import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Window 2.12
import QtQuick.Layouts 1.12
import QtGraphicalEffects 1.12

/**
 * 独立的地图全屏窗口
 * 使用OfflineMapViewer组件，提供真正的全屏地图体验
 * 集成完整的路线规划功能
 */
ApplicationWindow {
    id: standaloneMapWindow
    visible: false
    flags: Qt.Window | Qt.FramelessWindowHint
    color: "black"
    
    // 地图属性
    property real centerLon: 109.221465
    property real centerLat: 23.750306
    property real currentScale: 1.0
    
    // 路径规划面板显示状态
    property bool routePanelVisible: false
    
    // 信号定义
    signal mapReady()
    signal locationChanged(real lon, real lat)
    signal mapClicked(real lon, real lat)
    signal fullscreenClosed()
    signal pathChanged()
    signal pathPointAdded(real lon, real lat, int index)
    signal pathPointRemoved(int index)
    
    // 标记点模型
    ListModel {
        id: markersModel
    }
    
    // 离线地图查看器
    OfflineMapViewer {
        id: standaloneMap
        anchors.fill: parent
        anchors.margins: 0
        
        // 同步属性
        currentScale: standaloneMapWindow.currentScale
        
        onCurrentScaleChanged: {
            // 当缩放级别改变时，更新窗口的缩放属性
            standaloneMapWindow.currentScale = currentScale
        }
        
        onMapReady: {
            console.log("独立地图窗口准备就绪")
            standaloneMapWindow.mapReady()
        }
        
        onLocationChanged: function(lon, lat) {
            centerLon = lon
            centerLat = lat
            standaloneMapWindow.locationChanged(lon, lat)
        }
        
        onMapClicked: function(lon, lat) {
            standaloneMapWindow.mapClicked(lon, lat)
        }
        
        // 路径规划相关信号转发
        onPathChanged: {
            standaloneMapWindow.pathChanged()
        }
        
        onPathPointAdded: function(lon, lat, index) {
            standaloneMapWindow.pathPointAdded(lon, lat, index)
        }
        
        onPathPointRemoved: function(index) {
            standaloneMapWindow.pathPointRemoved(index)
        }
    }
    
    // 全屏控制按钮
    Row {
        id: fullscreenControls
        anchors.top: parent.top
        anchors.right: parent.right
        anchors.margins: 12
        spacing: 8
        
        // 退出全屏按钮
        Button {
            id: exitFullscreenButton
            width: 40
            height: 40
            
            background: Rectangle {
                color: parent.pressed ? Qt.rgba(255, 255, 255, 0.3) : Qt.rgba(255, 255, 255, 0.1)
                radius: 20
                border.color: Qt.rgba(255, 255, 255, 0.3)
                border.width: 1
            }
            
            contentItem: Text {
                text: "✕"
                color: Qt.rgba(255, 255, 255, 0.8)
                font.pixelSize: 16
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
            }
            
            onClicked: {
                closeFullscreen()
            }
            
            hoverEnabled: true
            onHoveredChanged: {
                if (hovered) {
                    background.color = Qt.rgba(255, 255, 255, 0.2)
                } else {
                    background.color = Qt.rgba(255, 255, 255, 0.1)
                }
            }
        }
        
        // 放大按钮
        Button {
            id: fullscreenZoomInButton
            width: 40
            height: 40
            
            background: Rectangle {
                color: parent.pressed ? Qt.rgba(255, 255, 255, 0.3) : Qt.rgba(255, 255, 255, 0.1)
                radius: 20
                border.color: Qt.rgba(255, 255, 255, 0.3)
                border.width: 1
            }
            
            contentItem: Text {
                text: "⛶"
                color: Qt.rgba(255, 255, 255, 0.8)
                font.pixelSize: 18
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
            }
            
            onClicked: {
                if (standaloneMap && standaloneMap.zoomIn) {
                    standaloneMap.zoomIn(0.2)
                }
            }
            
            hoverEnabled: true
            onHoveredChanged: {
                if (hovered) {
                    background.color = Qt.rgba(255, 255, 255, 0.2)
                } else {
                    background.color = Qt.rgba(255, 255, 255, 0.1)
                }
            }
        }
        
        // 缩小按钮
        Button {
            id: fullscreenZoomOutButton
            width: 40
            height: 40
            
            background: Rectangle {
                color: parent.pressed ? Qt.rgba(255, 255, 255, 0.3) : Qt.rgba(255, 255, 255, 0.1)
                radius: 20
                border.color: Qt.rgba(255, 255, 255, 0.3)
                border.width: 1
            }
            
            contentItem: Text {
                text: "⛷"
                color: Qt.rgba(255, 255, 255, 0.8)
                font.pixelSize: 18
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
            }
            
            onClicked: {
                if (standaloneMap && standaloneMap.zoomOut) {
                    standaloneMap.zoomOut(0.2)
                }
            }
            
            hoverEnabled: true
            onHoveredChanged: {
                if (hovered) {
                    background.color = Qt.rgba(255, 255, 255, 0.2)
                } else {
                    background.color = Qt.rgba(255, 255, 255, 0.1)
                }
            }
        }
        
        // 路径规划按钮
        Button {
            id: routePlanningButton
            width: 40
            height: 40
            
            background: Rectangle {
                color: parent.pressed ? Qt.rgba(255, 255, 255, 0.3) : Qt.rgba(255, 255, 255, 0.1)
                radius: 20
                border.color: Qt.rgba(255, 255, 255, 0.3)
                border.width: 1
            }
            
            contentItem: Text {
                text: "🗺️"
                color: Qt.rgba(255, 255, 255, 0.8)
                font.pixelSize: 16
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
            }
            
            onClicked: {
                routePanelVisible = !routePanelVisible
            }
            
            hoverEnabled: true
            onHoveredChanged: {
                if (hovered) {
                    background.color = Qt.rgba(255, 255, 255, 0.2)
                } else {
                    background.color = Qt.rgba(255, 255, 255, 0.1)
                }
            }
        }
    }
    
    // 路径规划控制面板
    Rectangle {
        id: routePlanningPanel
        anchors.left: parent.left
        anchors.top: parent.top
        anchors.margins: 12
        width: 280
        height: 380
        color: Qt.rgba(255, 255, 255, 0.95)
        radius: 8
        border.color: "#ddd"
        border.width: 1
        visible: routePanelVisible
        
        // 阴影效果
        layer.enabled: true
        layer.effect: DropShadow {
            horizontalOffset: 0
            verticalOffset: 2
            radius: 8
            samples: 16
            color: "#20000000"
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 12
            spacing: 8
            
            // 标题
            Text {
                text: "🗺️ 路径规划"
                font.pixelSize: 16
                font.bold: true
                color: "#2c3e50"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            // 分割线
            Rectangle {
                width: parent.width
                height: 1
                color: "#e9ecef"
            }
            
            // 编辑模式控制
            Button {
                text: standaloneMap.pathEditMode ? "退出编辑模式" : "进入编辑模式"
                width: parent.width
                height: 35
                
                background: Rectangle {
                    color: parent.enabled ? (standaloneMap.pathEditMode ? "#e74c3c" : "#27ae60") : "#ecf0f1"
                    border.color: parent.enabled ? (standaloneMap.pathEditMode ? "#c0392b" : "#229954") : "#bdc3c7"
                    border.width: 1
                    radius: 4
                }
                
                contentItem: Text {
                    text: parent.text
                    color: parent.enabled ? "white" : "#95a5a6"
                    font.pixelSize: 12
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
                
                onClicked: {
                    standaloneMap.togglePathEditMode()
                }
            }
            
            // 路径操作按钮组
            GridLayout {
                width: parent.width
                columns: 2
                rowSpacing: 8
                columnSpacing: 8
                
                Button {
                    text: "清除路径"
                    Layout.fillWidth: true
                    Layout.preferredHeight: 30
                    enabled: standaloneMap.pathPointsModel ? standaloneMap.pathPointsModel.count > 0 : false
                    
                    background: Rectangle {
                        color: parent.enabled ? "#f39c12" : "#ecf0f1"
                        border.color: parent.enabled ? "#e67e22" : "#bdc3c7"
                        border.width: 1
                        radius: 4
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: parent.enabled ? "white" : "#95a5a6"
                        font.pixelSize: 11
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        standaloneMap.clearPath()
                    }
                }
                
                Button {
                    text: "撤销上一点"
                    Layout.fillWidth: true
                    Layout.preferredHeight: 30
                    enabled: standaloneMap.pathPointsModel ? standaloneMap.pathPointsModel.count > 0 : false
                    
                    background: Rectangle {
                        color: parent.enabled ? "#9b59b6" : "#ecf0f1"
                        border.color: parent.enabled ? "#8e44ad" : "#bdc3c7"
                        border.width: 1
                        radius: 4
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: parent.enabled ? "white" : "#95a5a6"
                        font.pixelSize: 11
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        standaloneMap.undoLastPathPoint()
                    }
                }
                
                Button {
                    text: "保存路径"
                    Layout.fillWidth: true
                    Layout.preferredHeight: 30
                    enabled: standaloneMap.pathPointsModel ? standaloneMap.pathPointsModel.count > 0 : false
                    
                    background: Rectangle {
                        color: parent.enabled ? "#3498db" : "#ecf0f1"
                        border.color: parent.enabled ? "#2980b9" : "#bdc3c7"
                        border.width: 1
                        radius: 4
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: parent.enabled ? "white" : "#95a5a6"
                        font.pixelSize: 11
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        saveCurrentPath()
                    }
                }
                
                Button {
                    text: "加载路径"
                    Layout.fillWidth: true
                    Layout.preferredHeight: 30
                    
                    background: Rectangle {
                        color: "#34495e"
                        border.color: "#2c3e50"
                        border.width: 1
                        radius: 4
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font.pixelSize: 11
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        loadPath()
                    }
                }
                
                Button {
                    text: "测试路径"
                    Layout.fillWidth: true
                    Layout.preferredHeight: 30
                    
                    background: Rectangle {
                        color: "#e67e22"
                        border.color: "#d35400"
                        border.width: 1
                        radius: 4
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font.pixelSize: 11
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        addTestPathPoints()
                    }
                }
                
            }
            
            // 分割线
            Rectangle {
                width: parent.width
                height: 1
                color: "#e9ecef"
            }
            
            // 路径统计信息
            Rectangle {
                width: parent.width
                height: 80
                color: standaloneMap.pathEditMode ? "#e8f5e8" : "#f8f9fa"
                border.color: standaloneMap.pathEditMode ? "#27ae60" : "#dee2e6"
                border.width: 1
                radius: 4
                visible: standaloneMap.pathPointsModel ? standaloneMap.pathPointsModel.count > 0 : false
                
                Column {
                    anchors.left: parent.left
                    anchors.top: parent.top
                    anchors.margins: 8
                    spacing: 4
                    
                    Text {
                        text: "编辑模式: " + (standaloneMap.pathEditMode ? "启用" : "禁用")
                        font.pixelSize: 11
                        color: standaloneMap.pathEditMode ? "#27ae60" : "#6c757d"
                        font.bold: standaloneMap.pathEditMode
                    }
                    
                    Text {
                        text: "路径点数: " + (standaloneMap.pathPointsModel ? standaloneMap.pathPointsModel.count : 0)
                        font.pixelSize: 11
                        color: "#495057"
                    }
                    
                    Text {
                        text: "路径长度: " + (standaloneMap.pathPointsModel && standaloneMap.pathPointsModel.count > 1 ? (standaloneMap.calculatePathLength() / 1000).toFixed(2) : "0.00") + " 公里"
                        font.pixelSize: 11
                        color: "#495057"
                        visible: standaloneMap.pathPointsModel ? standaloneMap.pathPointsModel.count > 1 : false
                    }
                }
            }
            
            // 使用说明
            Rectangle {
                width: parent.width
                height: 60
                color: "#e3f2fd"
                border.color: "#2196f3"
                border.width: 1
                radius: 4
                
                Column {
                    anchors.fill: parent
                    anchors.margins: 6
                    spacing: 2
                    
                    Text {
                        text: "使用说明"
                        font.pixelSize: 11
                        color: "#1976d2"
                        font.bold: true
                    }
                    
                    Text {
                        text: "• 进入编辑模式后点击地图添加路径点"
                        font.pixelSize: 9
                        color: "#495057"
                    }
                    
                    Text {
                        text: "• 右键点击路径点附近可删除"
                        font.pixelSize: 9
                        color: "#495057"
                    }
                    
                    Text {
                        text: "• 使用键盘快捷键: E=编辑, C=清除, S=保存"
                        font.pixelSize: 9
                        color: "#495057"
                    }
                }
            }
        }
    }
    
    // 路径状态显示
    Rectangle {
        anchors.bottom: parent.bottom
        anchors.left: parent.left
        anchors.margins: 12
        width: 300
        height: 80
        color: Qt.rgba(0, 0, 0, 0.7)
        radius: 8
        visible: standaloneMap.pathPointsModel ? standaloneMap.pathPointsModel.count > 0 : false
        
        // 阴影效果
        layer.enabled: true
        layer.effect: DropShadow {
            horizontalOffset: 0
            verticalOffset: 2
            radius: 8
            samples: 16
            color: "#20000000"
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 8
            spacing: 4
            
            Text {
                text: "路径点数: " + (standaloneMap.pathPointsModel ? standaloneMap.pathPointsModel.count : 0)
                color: "white"
                font.pixelSize: 12
                font.bold: true
            }
            
            Text {
                text: "路径长度: " + (standaloneMap.pathPointsModel && standaloneMap.pathPointsModel.count > 1 ? (standaloneMap.calculatePathLength() / 1000).toFixed(2) : "0.00") + " 公里"
                color: "white"
                font.pixelSize: 12
                visible: standaloneMap.pathPointsModel ? standaloneMap.pathPointsModel.count > 1 : false
            }
            
            Text {
                text: "编辑模式: " + (standaloneMap.pathEditMode ? "启用" : "禁用")
                color: standaloneMap.pathEditMode ? "#e74c3c" : "#27ae60"
                font.pixelSize: 12
                font.bold: true
            }
        }
    }
    
    // 键盘事件处理
    Keys.onEscapePressed: {
        if (routePanelVisible) {
            routePanelVisible = false
        } else {
            closeFullscreen()
        }
    }
    
    Keys.onPressed: {
        switch (event.key) {
            case Qt.Key_Plus:
            case Qt.Key_Equal:
                if (standaloneMap && standaloneMap.zoomIn) {
                    standaloneMap.zoomIn(0.2)
                }
                break
            case Qt.Key_Minus:
                if (standaloneMap && standaloneMap.zoomOut) {
                    standaloneMap.zoomOut(0.2)
                }
                break
            case Qt.Key_F11:
                if (visibility === Window.FullScreen) {
                    visibility = Window.Windowed
                } else {
                    visibility = Window.FullScreen
                }
                break
            // 路径规划快捷键
            case Qt.Key_E:
                // E键切换编辑模式
                if (standaloneMap) {
                    standaloneMap.togglePathEditMode()
                }
                break
            case Qt.Key_C:
                // C键清除路径
                if (standaloneMap && standaloneMap.pathPointsModel && standaloneMap.pathPointsModel.count > 0) {
                    standaloneMap.clearPath()
                }
                break
            case Qt.Key_S:
                // S键保存路径
                if (standaloneMap && standaloneMap.pathPointsModel && standaloneMap.pathPointsModel.count > 0) {
                    saveCurrentPath()
                }
                break
            case Qt.Key_L:
                // L键加载路径
                loadPath()
                break
            case Qt.Key_R:
                // R键显示/隐藏路径规划面板
                routePanelVisible = !routePanelVisible
                break
            case Qt.Key_U:
                // U键撤销最后一个路径点
                if (standaloneMap && standaloneMap.pathPointsModel && standaloneMap.pathPointsModel.count > 0) {
                    standaloneMap.undoLastPathPoint()
                }
                break
        }
    }
    
    // 显示全屏地图
    function showFullscreen(lon, lat, scale) {
        console.log("显示独立全屏地图")
        
        // 设置地图参数
        if (lon !== undefined && lat !== undefined) {
            centerLon = lon
            centerLat = lat
        }
        if (scale !== undefined) {
            currentScale = scale
        }
        
        // 同步地图状态
        if (standaloneMap && standaloneMap.setMapCenter) {
            standaloneMap.setMapCenter(centerLon, centerLat)
        }
        if (standaloneMap && standaloneMap.setScale) {
            standaloneMap.setScale(currentScale)
        }
        
        // 设置窗口尺寸为屏幕尺寸
        if (Screen) {
            width = Screen.width
            height = Screen.height
        }
        
        // 设置为全屏模式
        visibility = Window.FullScreen
        visible = true
        
        // 设置焦点以接收键盘事件
        forceActiveFocus()
        
        console.log("独立全屏地图已打开")
    }
    
    // 关闭全屏地图
    function closeFullscreen() {
        visible = false
        visibility = Window.Windowed
        fullscreenClosed()
        console.log("独立全屏地图已关闭")
    }
    
    // 设置地图中心点
    function setMapCenter(lon, lat) {
        centerLon = lon
        centerLat = lat
        
        if (standaloneMap && standaloneMap.setMapCenter) {
            standaloneMap.setMapCenter(lon, lat)
        }
    }
    
    // 设置缩放级别
    function setScale(scale) {
        currentScale = scale
        
        if (standaloneMap && standaloneMap.setScale) {
            standaloneMap.setScale(scale)
        }
    }
    
    // 添加标记点
    function addMarker(lon, lat, title, content) {
        if (standaloneMap && standaloneMap.addMarker) {
            standaloneMap.addMarker(lon, lat, title, content)
        }
    }
    
    // 获取当前位置
    function getCurrentLocation() {
        return { lon: centerLon, lat: centerLat }
    }
    
    // 清除所有标记
    function clearMarkers() {
        if (standaloneMap && standaloneMap.clearMarkers) {
            standaloneMap.clearMarkers()
        }
    }
    
    // ==================== 路径规划相关函数 ====================
    
    // 保存当前路径
    function saveCurrentPath() {
        if (standaloneMap && standaloneMap.pathPointsModel && standaloneMap.pathPointsModel.count > 0) {
            var pathData = {
                name: "独立地图路径_" + new Date().toISOString().slice(0, 19).replace(/:/g, '-'),
                timestamp: new Date().toISOString(),
                points: standaloneMap.getPathPoints(),
                totalLength: standaloneMap.calculatePathLength(),
                pointCount: standaloneMap.pathPointsModel.count
            }
            console.log("保存路径数据:", pathData)
            console.log("路径点数:", pathData.pointCount)
            console.log("路径长度:", (pathData.totalLength / 1000).toFixed(2), "公里")
            // 这里可以添加文件保存对话框
            return pathData
        } else {
            console.log("没有路径点可保存")
            return null
        }
    }
    
    // 加载路径
    function loadPath() {
        console.log("加载路径功能")
        // 这里可以添加文件选择对话框
        // 或者加载示例路径
        var samplePath = [
            { lon: 109.240150, lat: 23.724696 },
            { lon: 109.242150, lat: 23.726696 },
            { lon: 109.244150, lat: 23.728696 },
            { lon: 109.246150, lat: 23.730696 }
        ]
        
        if (standaloneMap && standaloneMap.setPathPoints) {
            standaloneMap.setPathPoints(samplePath)
            console.log("已加载示例路径，包含", samplePath.length, "个点")
        }
    }
    
    // 显示路径统计信息
    function showPathStatistics() {
        if (standaloneMap && standaloneMap.getPathStatistics) {
            var stats = standaloneMap.getPathStatistics()
            console.log("路径统计信息:")
            console.log("- 路径点数:", stats.pointCount)
            console.log("- 总长度:", (stats.totalLength / 1000).toFixed(2), "公里")
            console.log("- 平均段长度:", (stats.averageSegmentLength / 1000).toFixed(2), "公里")
            console.log("- 最小段长度:", (stats.minSegmentLength / 1000).toFixed(2), "公里")
            console.log("- 最大段长度:", (stats.maxSegmentLength / 1000).toFixed(2), "公里")
            return stats
        }
        return null
    }
    
    // 导出路径为KML格式
    function exportPathToKML() {
        if (standaloneMap && standaloneMap.exportPathToKML) {
            var kmlContent = standaloneMap.exportPathToKML()
            console.log("KML导出完成，内容长度:", kmlContent.length)
            return kmlContent
        }
        return ""
    }
    
    // 导入路径从KML格式
    function importPathFromKML(kmlContent) {
        if (standaloneMap && standaloneMap.importPathFromKML) {
            var result = standaloneMap.importPathFromKML(kmlContent)
            console.log("KML导入结果:", result)
            return result
        }
        return false
    }
    
    // 添加测试路径点
    function addTestPathPoints() {
        if (standaloneMap) {
            // 清除现有路径
            standaloneMap.clearPath()
            
            // 添加测试路径点
            var testPoints = [
                { lon: 109.240150, lat: 23.724696 },
                { lon: 109.242150, lat: 23.726696 },
                { lon: 109.244150, lat: 23.728696 },
                { lon: 109.246150, lat: 23.730696 },
                { lon: 109.248150, lat: 23.732696 }
            ]
            
            for (var i = 0; i < testPoints.length; i++) {
                standaloneMap.addPathPoint(testPoints[i].lon, testPoints[i].lat)
            }
            
            console.log("已添加测试路径点，共", testPoints.length, "个点")
        }
    }
    
    
    // 窗口初始化
    Component.onCompleted: {
        console.log("独立地图窗口组件初始化完成")
    }
    
    // 窗口销毁
    Component.onDestruction: {
        console.log("独立地图窗口组件即将销毁")
    }
}